<template>
	<view class="address">
		<!-- 导航栏 -->
		<nav-bar></nav-bar>
		<!-- 地址列表 -->
		<view class="address-list">
			<view 
				class="address-item"
				v-for="address in addressList"
				:key="address.id"
			>
				<view class="address-info">
					<view class="user-info">
						<view class="left">
							<text class="name">{{ address.recipientName }}</text>
							<text class="phone">{{ address.recipientPhone }}</text>
							<text v-if="address.tag" class="tag">{{ address.tag }}</text>
						</view>
						<view class="right">
							<label class="default-address">
								<radio 
									:checked="address.isDefault === 1" 
									:value="address.id.toString()"
									@click="setDefaultAddress(address)"
									color="#2B87FF"
								/>
								默认地址
							</label>
						</view>
					</view>
					<text class="address-text">{{ address.fullAddress }}</text>
				</view>
				<view class="operations">
					<view class="edit" @tap="editAddress(address)">
						<text class="icon">✎</text>
						<text>编辑</text>
					</view>
					<view class="delete" @tap="deleteAddress(address)">
						<text class="icon">✕</text>
						<text>删除</text>
					</view>
				</view>
			</view>
			
			<!-- 空状态提示 -->
			<view class="empty-state" v-if="addressList.length === 0">
				<image src="/static/images/empty-address.png" mode="aspectFit" class="empty-image"></image>
				<text class="empty-text">暂无收货地址</text>
				<text class="empty-tip">点击下方按钮添加新地址</text>
			</view>
		</view>
		
		<!-- 添加地址按钮 -->
		<view class="add-btn" @tap="addAddress">
			<text>新增地址</text>
		</view>
	</view>
</template>

<script>
import NavBar from '@/components/nav-bar/nav-bar.vue'
export default {
	components: {
		NavBar
	},
	data() {
		return {
			addressList: []
		}
	},
	
	onLoad() {
		this.loadAddressList()
	},
	onShow() {
		this.loadAddressList()
	},
	
	methods: {
		// 加载地址列表
		loadAddressList() {
			const userInfoStr = uni.getStorageSync('userInfo')
			let userInfo = null
			
			if (userInfoStr) {
			  try {
			    // 如果是字符串，尝试解析
			    if (typeof userInfoStr === 'string') {
			      const parsed = JSON.parse(userInfoStr)
			      // 检查是否是登录响应格式
			      if (parsed.code === 200 && parsed.data) {
			        userInfo = parsed.data
			      } else {
			        userInfo = parsed
			      }
			    } else {
			      // 如果不是字符串，直接使用
			      userInfo = userInfoStr
			    }
			  } catch (e) {
			    console.error('解析用户信息失败', e)
			    // 解析失败时，尝试直接使用
			    userInfo = userInfoStr
			  }
			}
			const memberId = userInfo.memberId
			
			uni.request({
				url: `${uni.$config.baseUrl}/address/address/listAll`,
				method: 'GET',
				data: {
					id: memberId
				},
				success: (res) => {
					if (res.statusCode === 200 && res.data && res.data.code === 200) {
						// 对地址列表进行排序，默认地址排在最前面
						const addresses = res.data.rows || []
						this.addressList = addresses.sort((a, b) => {
							// isDefault为1的排在前面
							if (a.isDefault === 1 && b.isDefault !== 1) return -1
							if (a.isDefault !== 1 && b.isDefault === 1) return 1
							// 如果isDefault相同，按id排序
							return b.id - a.id
						})
					} else {
						uni.showToast({
							title: res.data.msg || '获取地址列表失败',
							icon: 'none'
						})
					}
				},
				fail: (err) => {
					console.error('获取地址列表失败:', err)
					uni.showToast({
						title: '网络请求失败',
						icon: 'none'
					})
				}
			})
		},
		
		// 新增地址
		addAddress() {
			uni.navigateTo({
				url: '/pages/address/edit-address'
			})
		},
		
		// 编辑地址
		editAddress(address) {
			uni.navigateTo({
				url: `/pages/address/edit-address?addressInfo=${encodeURIComponent(JSON.stringify(address))}`
			})
		},
		
		// 删除地址
		deleteAddress(address) {
			uni.showModal({
				title: '提示',
				content: '确定要删除该地址吗？',
				success: (res) => {
					if (res.confirm) {
						uni.request({
							url: `${uni.$config.baseUrl}/address/address/${address.id}`,
							method: 'DELETE',
							success: (res) => {
								if (res.statusCode === 200 && res.data.code === 200) {
									// 从列表中移除被删除的地址
									this.addressList = this.addressList.filter(item => item.id !== address.id)
									uni.showToast({
										title: '删除成功',
										icon: 'success'
									})
								} else {
									uni.showToast({
										title: res.data.msg || '删除失败',
										icon: 'none'
									})
								}
							},
							fail: (err) => {
								console.error('删除地址失败:', err)
								uni.showToast({
									title: '网络请求失败',
									icon: 'none'
								})
							}
						})
					}
				}
			})
		},
		
		// 设置默认地址
		setDefaultAddress(address) {
			if (address.isDefault === 1) {
				return; // 如果已经是默认地址，不做任何操作
			}
			
			const userInfoStr = uni.getStorageSync('userInfo')
			if (!userInfoStr) {
				uni.showToast({
					title: '请先登录',
					icon: 'none'
				})
				return
			}
			
			uni.request({
				url: `${uni.$config.baseUrl}/address/address/setDefault/${address.id}`,
				method: 'PUT',
				success: (res) => {
					if (res.statusCode === 200 && res.data.code === 200) {
						// 更新地址列表中的默认状态
						this.addressList.forEach(item => {
							item.isDefault = item.id === address.id ? 1 : 0
						})
						
						uni.showToast({
							title: '设置成功',
							icon: 'success',
							duration: 1500,
							success: () => {
								// 延迟跳转，让用户看到成功提示
								setTimeout(() => {
									// 获取上一页实例
									const pages = getCurrentPages()
									const prevPage = pages[pages.length - 2]
									
									// 如果上一页存在，调用其刷新方法
									if (prevPage) {
										// 检查上一页是否有loadAddressList方法
										if (prevPage.$vm && typeof prevPage.$vm.loadAddressList === 'function') {
											prevPage.$vm.loadAddressList()
										}
									}
									
									// 返回上一页
									uni.navigateBack({
										delta: 1
									})
								}, 1500)
							}
						})
					} else {
						uni.showToast({
							title: res.data.msg || '设置失败',
							icon: 'none'
						})
					}
				},
				fail: (err) => {
					console.error('设置默认地址失败:', err)
					uni.showToast({
						title: '网络请求失败',
						icon: 'none'
					})
				}
			})
		},
	}
}
</script>

<style lang="scss">
.address {
	min-height: 100vh;
	background: #F8F8F8;
	padding-bottom: calc(140rpx + env(safe-area-inset-bottom));
	
	.address-list {
		padding: 20rpx;
		
		.empty-state {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			padding: 100rpx 0;
			
			.empty-image {
				width: 240rpx;
				height: 240rpx;
				margin-bottom: 30rpx;
			}
			
			.empty-text {
				font-size: 32rpx;
				color: #333;
				font-weight: 500;
				margin-bottom: 16rpx;
			}
			
			.empty-tip {
				font-size: 28rpx;
				color: #999;
			}
		}
		
		.address-item {
			background: #FFFFFF;
			border-radius: 12rpx;
			padding: 30rpx;
			margin-bottom: 20rpx;
			
			.address-info {
				.user-info {
					display: flex;
					justify-content: space-between;
					align-items: center;
					margin-bottom: 16rpx;
					
					.left {
						display: flex;
						align-items: center;
						
						.name {
							font-size: 30rpx;
							color: #333;
							font-weight: 500;
							margin-right: 20rpx;
						}
						
						.phone {
							font-size: 28rpx;
							color: #666;
							margin-right: 20rpx;
						}
						
						.tag {
							font-size: 24rpx;
							color: #2B87FF;
							background: rgba(43, 135, 255, 0.1);
							padding: 4rpx 12rpx;
							border-radius: 4rpx;
						}
					}
					
					.right {
						.default-address {
							display: flex;
							align-items: center;
							font-size: 26rpx;
							color: #666;
							
							radio {
								transform: scale(0.8);
								margin-right: 8rpx;
							}
						}
					}
				}
				
				.address-text {
					font-size: 28rpx;
					color: #333;
					line-height: 1.4;
				}
			}
			
			.operations {
				display: flex;
				justify-content: flex-end;
				margin-top: 20rpx;
				padding-top: 20rpx;
				border-top: 1rpx solid #EEEEEE;
				
				.edit, .delete {
					display: flex;
					align-items: center;
					padding: 10rpx 20rpx;
					font-size: 26rpx;
					
					.icon {
						font-size: 28rpx;
						margin-right: 6rpx;
					}
				}
				
				.edit {
					color: #2B87FF;
					margin-right: 30rpx;
				}
				
				.delete {
					color: #FF5B5B;
				}
			}
		}
	}
	
	.add-btn {
		position: fixed;
		left: 40rpx;
		right: 40rpx;
		bottom: calc(40rpx + env(safe-area-inset-bottom));
		height: 88rpx;
		background: #2B87FF;
		color: #FFFFFF;
		font-size: 32rpx;
		border-radius: 44rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		
		&:active {
			transform: scale(0.98);
			opacity: 0.9;
		}
	}
}
</style> 